package com.aimee.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.aimee.util.ReadExcel;


/**
 * 上传文件批量添加用户
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    // 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  //上传后的文件存哪？
	  //1 本项目下upload下，好处是html网页可直接访问，坏处是资源紧张
	  //2 放到别的服务器，好处是不占用本项目资源，http://项目/文件夹/temo.jpg
		
		 DiskFileItemFactory factory = new DiskFileItemFactory();// 配置上传参数      
        factory.setSizeThreshold(MEMORY_THRESHOLD);  // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // 设置临时存储目录
        ServletFileUpload upload = new ServletFileUpload(factory);      
        upload.setFileSizeMax(MAX_FILE_SIZE); // 设置最大文件上传值        
        upload.setSizeMax(MAX_REQUEST_SIZE);// 设置最大请求值 (包含文件和表单数据)
        upload.setHeaderEncoding("UTF-8");         // 中文处理
  
        String path=request.getServletContext().getRealPath("/upload");
        System.out.println(path);
        // 如果目录不存在则创建
        File uploadDir = new File(path);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        //如何提取表单数据
        File storeFile=null;
        try {
			List<FileItem> formitems=upload.parseRequest(request);
		  if(formitems!=null&&formitems.size()>0) {
			for (FileItem item : formitems) {//username,pass,file
				if(!item.isFormField()) {
					String filename=item.getName();//文件名
					String filepath=path+File.separator+filename;
					System.out.println("在上传文件"+filepath);
					//上传文件
					storeFile=new File(filepath);
					item.write(storeFile);
				}
			}
			//上传成功后工具类 导入数据库
			System.out.println("上传成功");
			ReadExcel.importExcel(storeFile);
		  }
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
